package com.bw.module_main

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.*
import androidx.appcompat.app.AppCompatActivity
import android.provider.Settings
import android.view.LayoutInflater
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.lib_base.cons.RouterConst
import com.bw.module_main.databinding.ActivityMainBinding
import com.flyco.tablayout.CommonTabLayout
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import me.majiajie.pagerbottomtabstrip.NavigationController
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener
import org.greenrobot.eventbus.EventBus

@Route(path = RouterConst.PATH_MAIN_ACTIVITY)
class MainActivity : AppCompatActivity() {
    private lateinit var mNavController: NavigationController
    private lateinit var fragmentAdapter: FragmentAdapter
    private var listFragment: MutableList<Fragment> = mutableListOf()
    private var isFromUserInteraction: Boolean = false
    private var hasUnGranted = false
    private lateinit var binding:ActivityMainBinding

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        initView()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun autoRequestPermission(): Boolean {
        //是否是安卓6.0以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            //清理一下
            unGrantPermission.clear()

            needUserPermissions.forEach {
                var state = checkSelfPermission(it)
                if (state == PackageManager.PERMISSION_DENIED) {//还没有授权
                    unGrantPermission.add(it)
                }
            }

            //发起授权请求
            if (unGrantPermission.size > 0) {
                requestPermissions(unGrantPermission.toTypedArray(), 102)
                return false
            }
        }

        return true
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        //对于用户权限授权结果校验
        if (requestCode == 102 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            unGrantPermission.forEach {
                if (checkSelfPermission(it) == PackageManager.PERMISSION_DENIED) {
                    hasUnGranted = true
                }
            }
        }

        //如果存在，给Dialog提示即可
        if (hasUnGranted) {
            AlertDialog.Builder(this)
                .setTitle("权限申请")
                .setMessage("您拒绝了权限申请，请前往设置->应用管理->权限管理中开启权限")
                .setPositiveButton("去设置") { _, _ ->
                    //跳转到应用设置
                    hasUnGranted = false
                    openAppDetailPage()
                }
                .setNegativeButton("取消") { _, _ ->
                    hasUnGranted = false
                }
                .setNegativeButton("取消") { _, _ -> }
        }

    }

    private fun openAppDetailPage() {
        var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName, null)
        this.startActivity(intent)
    }

    private var unGrantPermission = arrayListOf<String>()

    @RequiresApi(Build.VERSION_CODES.M)
    private val mHandle = Handler(Looper.getMainLooper()) {
        when (it.what) {
            10 -> {
                autoRequestPermission()
            }
            else -> {}
        }
        true
    }

    //需要用户授权项
    private var needUserPermissions = arrayListOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.READ_PHONE_NUMBERS,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
    )


    @RequiresApi(Build.VERSION_CODES.M)
    fun initView() {


        mNavController = binding.mainBottomNav.custom()
            .addItem(newTabItem(R.drawable.home_normal, R.drawable.home_select, "首页"))
            .addItem(newTabItem(R.drawable.screening_normal, R.drawable.screening_select, "放映厅"))
            .addItem(NavAddTabItem(this))
            .addItem(newTabItem(R.drawable.live_normal, R.drawable.live_select, "直播"))
            .addItem(newTabItem(R.drawable.mine_normal, R.drawable.mine_select, "我的"))
            .build()

//        listFragment.add(
//            ARouter.getInstance().build(RoutePath.PATH_HOME_FRAGMENT).navigation() as Fragment
//        )
//        listFragment.add(
//            ARouter.getInstance().build(RoutePath.PATH_SERVICE_FRAGMENT).navigation() as Fragment
//        )
//        listFragment.add(
//            ARouter.getInstance().build(RoutePath.PATH_MESSAGE_FRAGMENT).navigation() as Fragment
//        )
//        listFragment.add(
//            ARouter.getInstance().build(RoutePath.PATH_NOTICE_FRAGMENT).navigation() as Fragment
//        )
//        listFragment.add(
//            ARouter.getInstance().build(RoutePath.PATH_MINE_FRAGMENT).navigation() as Fragment
//        )

        fragmentAdapter = FragmentAdapter(this, listFragment)
        binding.mainVp2.adapter = fragmentAdapter
        binding.mainVp2.offscreenPageLimit = 4

        mNavController.addTabItemSelectedListener(object : OnTabItemSelectedListener {
            override fun onSelected(index: Int, old: Int) {
                if (binding.mainVp2.currentItem != index) {
                    isFromUserInteraction = true
                    binding.mainVp2.setCurrentItem(index, true)
                }

                when(index){
                    0->{}
                    1->{}
                    2->{}
                    3->{}
                    4->{}
                }
            }

            override fun onRepeat(index: Int) {

            }
        })

        // ViewPager2 滑动 → 更新 Tab
        binding.mainVp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                mNavController.setSelect(position)
            }
        })
        var message = Message.obtain().apply {
            what = 10
            obj = 90
        }
        mHandle.sendMessageDelayed(message, 2000)

    }


    private fun newTabItem(defaultResId: Int, checkedResId: Int, title: String): BaseTabItem {
        var normalTabView = NavTabItem(this).apply {
            initData(defaultResId, checkedResId, title)
        }
        return normalTabView
    }
}